<template>
<div class="container">
    <div class="login-page">
    <van-tabs model:active="active" animated>
      <van-tab title="密码登录" class="tablists">
        <van-form
          @submit="onSubmit"
          validate-trigger="onSubmit"
          ref="loginForm"
          :show-error="false"
        >
          <van-cell-group>
            <van-field
              left-icon="column"
              v-model.trim="loginForm.username"
              name="username"
              placeholder="请输入您的手机号码"
              length="11"
              :rules="[{ validator: usernameValidator }]"
            />
            <van-field
              left-icon="lock"
              :right-icon="showPass ? 'closed-eye' : 'eye'"
              v-model.trim="loginForm.password"
              :type="showPass ? 'password' : 'text'"
              name="password"
              placeholder="请输入您的密码"
              minlength="8"
              :rules="[{ validator: passwordValidator }]"
              @click-right-icon="showPassword"
            />
          </van-cell-group>
          <div class="loginIn">
            <p class="firstTip">首次使用请使用验证码方式进行登陆</p>
            <van-button
              class="loginIn-btn"
              block
              type="primary"
              native-type="submit"
            >
              登录
            </van-button>
          </div>
          <div class="moreInfo">
            <span
              >点击查看
              <i class="tip" is-link @click="showPopup">《用户须知》</i></span
            >
            <span class="fr" @click="forgetPass">忘记密码</span>
          </div>
        </van-form>
      </van-tab>
      <van-tab title="验证码登录" class="tablists">
        <van-form
          validate-trigger="onSubmits"
          ref="codeForm"
          :show-error="false"
        >
          <van-cell-group>
            <van-field
              left-icon="column"
              v-model.trim="codeForm.username"
              name="username"
              placeholder="请输入您的手机号码"
              length="11"
              :rules="[{ validator: usernameValidator }]"
            />
            <div class="clearfix">
              <van-field
                type="number"
                length="4"
                :style="{ width: '52%', float: 'left', margin: '0 auto' }"
                left-icon="checked"
                v-model.trim="codeForm.code"
                name="code"
                placeholder="验证码"
              />
              <van-button
                class="codeBtn"
                :disabled="isSend"
                @click="showCode"
              >
                {{codeName}}
              </van-button>

             
            </div>
          </van-cell-group>
          <div class="loginIn">
            <p class="firstTip">首次使用请使用验证码方式进行登陆</p>
            <van-button
           
              class="loginIn-btn"
              block
              type="primary"
              native-type="submit"
              @click="verifyCode"
            >
              登录
            </van-button>
          </div>
          <div class="moreInfo">
            <span
              >点击查看
              <i class="tip" is-link @click="showPopup">《用户须知》</i></span
            >
          </div>
        </van-form>
      </van-tab>
    </van-tabs>

    <van-popup
      class="userInfo"
      v-model="show"
      round
    >
   
       <div class="">
        <div v-html="tipInfo"  :style="{margin: '20px 15px',textAlign:'justify'}"></div>
       </div> 
      <van-button
            class="loginIn-btn"
            block
            type="primary"
            :style="{ width: '80%', margin: '20px auto' }"
            @click="closeW"
          >
            知道了~
          </van-button>
    
    </van-popup>


    <van-popup @close="handleClose"
      class="codeTip"
      v-model="showCodes"
      round
      :style="{ width: '80%', padding: '20px' }"
    >
      <div>
        <h2 class="h2">输入数字获取短信验证码</h2>

        <div class="login-code" @click="refreshCode">
          <sidentify :identifyCode="identifyCode" />
        </div>

        <p @click="refreshCode" class="refreshC">看不清换一个</p>
      </div>
  
        <div class="codeList">
            <input class="code-input" 
              v-for="(input, index) in inputs"
              :key="index"
              v-model="input.value"
              :maxlength="input.maxlength"
              :autofocus="input.autofocus"
              @input="handleInput(index)"
              ref="input"
            />
          </div>

    </van-popup>

  </div>
  <div v-html="sutips" class="sutips"></div>
</div>

</template>

<script>
import sidentify from "../components/sidentify.vue";
import path from "../api/network.js";
import { Toast } from "vant";
export default {
  name: "App",
  components: {
    sidentify,
  },

  data() {
    return {
      active: 0,
      show: false,
      showCodes: false,
      identifyCodes: "1234567890",
      identifyCode: "",
      isSend: false,  //禁用
      codeName: "发送验证码",
      totalTime: 60, //一般是60
      timer:'', //定时器

      showPass: true,
      loginForm: {
        username: "",
        password: "",
      },
      inputs: [
        { value: '', maxlength: 1, autofocus:true},
        { value: '', maxlength: 1, autofocus:false},
        { value: '', maxlength: 1, autofocus:false},
        { value: '', maxlength: 1, autofocus:false },
      ], 

      codeForm: {
        username: "",
        code: "",
      },
      // usernamePattern: /^1[3456789]\d{9}$/,
      usernamePattern: /^1\d{10}$/,
      passwordPattern:
        // /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{8,64}$/,
         /^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z0-9]{8,15}$/,
      bannerImg:'',//banner图
      tipInfo:'',//用户须知
      retips:'',//结果页提示
      sutips:'',//技术支持
    };
    
    
  },
  created() {
    //初始化验证码
    //this.refreshCode();
  },
  mounted() {
    this.identifyCode = "";
    //this.makeCode(this.identifyCodes, 4);
    // this.testMethod('hm1989_+')
    this.getCon();
    const originalHeight=document.documentElement.clientHeight ||document.body.clientHeight;
            window.onresize = ()=>{
                return(()=>{
                    //键盘弹起与隐藏都会引起窗口的高度发生变化
                    const resizeHeight=document.documentElement.clientHeight || document.body.clientHeight;
                    console.log("进入到判断页面高度=========");
                    console.log("页面初始高度========="+originalHeight);
                    console.log("软键盘弹起高度========="+resizeHeight);
                    if(resizeHeight-0<originalHeight-0){
                    //当软键盘弹起，在此处操作
                    console.log("进入到软键盘弹起=========");
                        document.querySelector('body').setAttribute('style', 'height:'+originalHeight+'px;');
                        this.scrollerHeight=resizeHeight;
                    }else{
                    //当软键盘收起，在此处操作
                    console.log("进入到软键盘收起=========");
                    document.querySelector('body').setAttribute('style', 'height:100%;');
                    this.scrollerHeight="100%";
                    }
                })()

            }
  },
 computed:{
   
 },
  methods: {
    handleClose(){
      this.showCodes = false   //关闭对话框
      this.identifyCode=''     //重置

    },
      countDown() {
          if (this.isSend) return
          //this.sendCode() // 获取验证码的接口
          this.isSend = true
          this.codeName = this.totalTime + 's后重新发送'
          this.timer = setInterval(() => {
            this.totalTime--
            this.codeName = this.totalTime + 's后重新发送'
            if (this.totalTime < 0) {
            clearInterval(this.timer)
            this.codeName = '发送验证码'
            this.totalTime = 60
            this.isSend = false 
            }
            }, 1000)
          },


    handleInput(index) {
      const input = this.inputs[index];
      if (input.value.length === input.maxlength) {
        if (index < this.inputs.length - 1) {
          // 当前输入框已输入满，将焦点自动移动到下一个输入框
          this.$nextTick(() => {
            // console.log(this.$refs['input'][index+1])
            this.$refs['input'][index+1].focus();
            // this.$refs[`input-${index + 1}`][0].focus();
          });
        } else {
          // 最后一个输入框已输入满，进行验证码校验
          const code = this.inputs.map((input) => input.value).join('');
           // console.log('code',code);
          if (this.validateCode(code)) {
            // 验证码正确，执行提交逻辑
            //this.submit();
          } else {
            // 验证码错误，给出提示或执行其他操作
             //Toast("验证码有误 请重试！");
          }
        }
      }
    },
    validateCode(code) {
      // 验证码校验逻辑
      if(code==this.identifyCode){
         this.showCodes = false;
         Toast("验证通过！");
        // this.countDown();
        this.sendCode();
      }else{
         Toast("验证失败！")
               
      this.inputs.forEach(( item, index)=> {
          item['value']='';
      })

      this.$nextTick(()=>{
        this.$refs['input'][0].focus();
      })

    
    }
  },
    // submit() {
    //   // 提交逻辑
    //   // ...
    // },

    testMethod(data) {
      const reg =
        /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{8,64}$/;
      if (reg.test(data)) {
        console.log("通过正则验证");
      } else {
        console.log("未通过正则验证");
      }
    },

    usernameValidator(val) {
      return new Promise((resolve, reject) => {
        if (val === "") {
          Toast("手机号不能为空");
          return resolve(false);
        } else if (val.length > 11 || val.length < 11) {
          Toast("手机号位数不正确！");
        } else if (!this.usernamePattern.test(val)) {
          Toast("手机格式不正确！");
          return resolve(false);
        } else {
          return resolve(true);
        }
      });
    },
    passwordValidator(val) {
      return new Promise((resolve, reject) => {
        if (val === "") {
          Toast("密码不能为空");
          return resolve(false);
        } else if (val.length < 8) {
          Toast("密码8位或以上");
        } else if (!this.passwordPattern.test(val)) {
          Toast("密码格式不正确！");
          return resolve(false);
        } else {
          return resolve(true);
        }
      });
    },

    showPassword() {
      // 显示隐藏密码
      this.showPass = !this.showPass;
    },
    showPopup() {
      this.show = true;
    },

    jumpInput() {
      this.$refs.barcodeMsg.focus(); // 自动获取焦点
    },
    showCode() {
      if(this.codeForm.username){
        this.showCodes = true;
        this.makeCode(this.identifyCodes,4); 
      }else{
        Toast('请输入手机号码！')
       return;
      }
    },

    closeW() {
      this.show = false;
      this.showCodes = false;
    },
    forgetPass() {
      this.$router.push({ name: "repas1" });
    },
    //  queryS(){
    //   this.$router.push({ name: 'res'})
    //  },

    onSubmit(values) {
      if (values) {
        this.login(values);
      } else {
        return false;
      }
    },
    verifyCode() {
      if (this.codeForm.code === "") {
        Toast("验证码不能为空");
        return;
      } else if (
        this.codeForm.code.length < 4 ||
        this.codeForm.code.length > 4
      ) {
        Toast("验证码位数不正确！");
      } else {
        this.verify();
      }
    },

    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },

    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
      this.inputs.forEach(( item, index)=> {
          item['value']='';
      })

    },

    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
    },

    sendCode() {
      path.vcode({
          phoneNumber: this.codeForm.username,
        })
        .then((res) => {
          if (res.status == 200) {
            //this.$router.push('/setpas')
            Toast("验证码已发送 请注意查收！");
            this.countDown()
          }
        });
    },

    login(values) {
      path.login({
          userName: values.username,
          password: values.password,
        })
        .then((res) => {
          if (res.status == 200) {
            setInterval(this.$router.push({name:'res'}), 3000)
          }
        });
    },

    verify() {
      path.verify({
          phoneNumber: this.codeForm.username,
          vcode: this.codeForm.code,
        })
        .then((res) => {
          if (res.status == 200) {
            if(res.data==0){
              this.$router.push({ name: "setpas" });
            }else{
              setInterval(this.$router.push({name:'res'}), 3000)
            }
            
          }
        });
    },

    //获取list
    getCon() {
      path.getContent().then((res) => {
        if (res.status == 200) {
            var data=res.data.rows;
           data.forEach(items => {
              //用户需知
              if(items.twoLevelId==1){
                 this.tipInfo=items.profiles
                //banner图
              }else if(items.twoLevelId==2){
                this.bannerImg=items.fakuImg
                this.$bus.$emit('bgImg', this.bannerImg)
              }else if(items.twoLevelId==3){
                  this.sutips=items.profiles
                  if( this.sutips){
                    this.$bus.$emit('supportUnit', this.sutips)
                  }
              }else{
                this.retips=items.profiles;
                  if( this.retips){
                    localStorage.setItem("retips",this.retips)
                  }
              }
            });
        }
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.moreInfo {
  font-size: 26px;
  margin: 20px 0;
}

.tip {
  font-style: normal;
  color: #bf1a20;
}

.userInfo {
  font-size: 26px;
  height:80%;
  width: 80%;
  padding:20px
}
.userInfo>div{
  height:87%;
  overflow-y: scroll;
  word-break: break-all;
  white-space: pre-line


}
.codeBtn {
  background: #f5f5f5;
  color: #bf1a20;
  border: none;
}

.codeTip {
  text-align: center;
}

.h2 {
  font-size: 40px;
  letter-spacing: 2px;
}

.refreshC {
  margin: 60px auto;
  font-size: 28px;
}

.codeList {
  display: flex;
}

.codeList .code-input {
  flex: 1;
  width: 25%;
  background: #fff;
  border: none;
  border-bottom: 2px solid #000;
  margin: 2%;
  text-align: center;
  font-size: 54px;
  font-weight: 600;
}

.codeList .van-field__control {
  background-color: #fff !important;
  text-align: center;
  font-size: 50px;
  font-weight: 600;
}
.codeBtn{
  width: 45%;
  float: right;
  font-size: 30px;
  font-weight: 500;
  height: 80px;
}
.firstTip{
  font-size:23px;
}

</style>
